package com.gaotu.ci.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.Date;

/**
 * Created by taoli on 2022/5/21.
 */
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    @Transactional(readOnly = false)
    public User createUser(String name, String pwd, LocalDate birtDay){
        User user = User.createUser(name, pwd, birtDay);
        this.userRepository.save(user);
        return user;
    }

    @Transactional(readOnly = true)
    public User getUserByName(String name){
        if (StringUtils.isEmpty(name)){
            return null;
        }
        return this.userRepository.getByName(name);
    }

    @Transactional(readOnly = true)
    public boolean checkPassword(String name, String pwd){
        User user = this.userRepository.getByName(name);
        if (user == null){
            return false;
        }
        return user.checkPwd(pwd);
    }

    @Transactional(readOnly = false)
    public void modifyPassword(Long userId, String oldPwd, String newPwd){
        User user = this.userRepository.getById(userId);
        if (user == null){
            return;
        }
        if (!user.checkPwd(oldPwd)){
            throw new RuntimeException("旧密码错误");
        }
        user.modifyPassword(newPwd);
        this.userRepository.save(user);
    }

    public User getUserById(Long userId) {
        return this.userRepository.getById(userId);
    }
}
